package com.sdcqjy.property.base;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.KeyEvent;
import android.view.View;

import com.sdcqjy.mylibrary.Logger;
import com.sdcqjy.mylibrary.widget.LoadDialog;
import com.sdcqjy.mylibrary.widget.ShowToast;
import com.sdcqjy.property.AppLL;
import com.sdcqjy.property.R;
import com.sdcqjy.property.activity.LoginActivity;

import rx.Subscription;

public class BaseFragment<T extends BaseContract.Presenter> extends Fragment {
    protected Handler handler;
    //private Call request;
    private Subscription request;
    private LoadDialog dialog;
    protected T presenter;

    public BaseFragment getThis() {
        return this;
    }

    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    public BaseFragment<T> setHandler(Handler handler) {
        this.handler = handler;
        return this;
    }

    public void sendMessage(int type, Object object) {
    }

    public LoadDialog getDialog() {
        return dialog;
    }

    //public void openLoadDialog(Call request) {
    public void openLoadDialog(Subscription request) {
        this.request = request;
        openLoadDialog();
    }

    public void openLoadDialog() {
        if (dialog == null) {
            dialog = new LoadDialog(getActivity());
            dialog.setColorSchemeResources(R.color.colorAccent, R.color.common_yellow);
            dialog.setOnCancelListener(d -> loadDialogCancel());
        }
        dialog.show();
    }

    protected void loadDialogCancel() {
        if (request != null) {
            request.unsubscribe();//cancel();//stop();
            request = null;
        }
    }

    public void dismissDialog() {
        if (dialog != null)
            dialog.dismiss();
    }

    public void applyError(int tResId) {
        String string = getString(tResId);
        applyError(string);
    }

    public void applyError(String t) {
        ShowToast.alertShortOfWhite(getActivity(), t);
    }

    protected boolean isLogin() {
        return isLogin(true);
    }

    protected boolean isLogin(boolean goLogin) {
        boolean login = AppLL.getAppLL().isLogin();
        if (goLogin && !login) {
            if (getActivity() != null) {
                getActivity().runOnUiThread(() -> LoginActivity.open(getActivity()));
            }
        }
        return login;
    }

    public void onDestroyView() {
        super.onDestroyView();
        if (presenter != null) presenter.onDestroy();
        if (request != null) request = null;
        presenter = null;
        handler = null;
        Logger.log("--BaseFragment--onDestroyView--", "--" + this.getClass().getName() + "--");
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return true;
    }
}